<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">axios取消请求</h2>
        <button class="btn btn-primary"> 发送请求 </button>
        <button class="btn btn-warning" > 取消请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //2.声明全局变量
        let cancel = null;
        // let source = axios.CancelToken.source()
        console.log(axios)
        let cancelToken = axios.CancelToken
        const oarginAxios = axios.create({
            baseURL: 'http://localhost:3000/',
            timeout: 5000
        })
        // 请求拦截器
        oarginAxios.interceptors.request.use((config) => {
            return config
        })
        // 响应拦截器
        oarginAxios.interceptors.response.use((response) => {
            return response.data
        })
        //发送请求
        btns[0].onclick = function(){
            if (cancel !== null) {
                cancel()
            }
            oarginAxios.get('posts', {
                cancelToken: cancelToken(function(c) {
                    cancel = c
                })
            }).then(res => {
                console.log(res)
                cancel = null
            })
        }

        //绑定第二个事件取消请求
        btns[1].onclick = function(){
            // console.log(source)
            // source.cancel();
            cancel()
        }
    </script>
</body>
</html>